<?php

namespace app\admin\controller\base;

use app\common\controller\Backend;
use think\Db;
/**
 * 二维码管理
 *
 * @icon fa fa-circle-o
 */
class Qr extends Backend
{
    
    /**
     * Qr模型对象
     * @var \app\admin\model\Qr
     */
    protected $model = null;
    /**
     * 万能码路径
     * @var [type]
     */
    private $path = ROOT_PATH . 'public/uploads/qr/';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\base\Qr;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
               Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $ids = $this->model->getLastInsID();
                        if(!$this->make($ids))  Db::rollback();
                         Db::commit();
                        $this->success();
                    } else {
                         Db::rollback();
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
    
     /**
     * 生成二维码
     * @return [type] [description]
     */
    private function make($ids = null){
        if(!$ids) return false;
        $row = $this->model->get($ids);
        $file_name = md5(time()).'.png';
        $file = $this->path . $file_name;
        $data = config('generate').url('index/index/qr','id='.$ids,'html',true);
        file_put_contents($file, file_get_contents($data));
        $params['qr'] = '/uploads/qr/'.$file_name;
        $result = $row->allowField(true)->save($params);
        return $result;
    }

}
